package com.brainshare.web.controller.an;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.brainshare.an.domain.AnMechanism;
import com.brainshare.an.domain.AnMechanismMember;
import com.brainshare.an.domain.AnWechatUser;
import com.brainshare.an.domain.AnWechatUserMechanism;
import com.brainshare.an.service.IAnMechanismMemberService;
import com.brainshare.an.service.IAnMechanismService;
import com.brainshare.an.service.IAnWechatUserMechanismService;
import com.brainshare.an.service.IAnWechatUserService;
import com.brainshare.common.utils.DateUtils;
import com.brainshare.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.brainshare.common.annotation.Log;
import com.brainshare.common.core.controller.BaseController;
import com.brainshare.common.core.domain.AjaxResult;
import com.brainshare.common.enums.BusinessType;
import com.brainshare.common.utils.poi.ExcelUtil;
import com.brainshare.common.core.page.TableDataInfo;

/**
 * 机构Controller
 *
 * @author ruoyi
 * @date 2022-11-05
 */
@RestController
@RequestMapping("/an/mechanism")
public class AnMechanismController extends BaseController {
    @Autowired
    private IAnMechanismMemberService anMechanismMemberService;
    @Autowired
    private IAnWechatUserMechanismService anWechatUserMechanismService;
    @Autowired
    private IAnMechanismService anMechanismService;
    @Autowired
    private IAnWechatUserService anWechatUserService;

    /**
     * 查询机构列表
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:list')")
    @GetMapping("/list")
    public TableDataInfo list(AnMechanism anMechanism) {
        startPage();
        List<AnMechanism> list = anMechanismService.selectAnMechanismList(anMechanism);
        return getDataTable(list);
    }

    /**
     * 导出机构列表
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:export')")
    @Log(title = "机构", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AnMechanism anMechanism) {
        List<AnMechanism> list = anMechanismService.selectAnMechanismList(anMechanism);
        for (AnMechanism mechanism : list) {
            if (StringUtils.isNotEmpty(mechanism.getBusinessLicense())) {
                String imgUrl = "https://www.ainaoxingdong.com/api" + mechanism.getBusinessLicense();
                mechanism.setBusinessLicense(imgUrl);
            }
        }
        ExcelUtil<AnMechanism> util = new ExcelUtil<AnMechanism>(AnMechanism.class);
        util.exportExcel(response, list, "机构数据");
    }

    /**
     * 获取机构详细信息
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:query')")
    @GetMapping(value = "/{mechanismId}")
    public AjaxResult getInfo(@PathVariable("mechanismId") Long mechanismId) {
        return success(anMechanismService.selectAnMechanismByMechanismId(mechanismId));
    }

    /**
     * 新增机构
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:add')")
    @Log(title = "机构", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AnMechanism anMechanism) {
        AnMechanism queryAnMechanism=new AnMechanism();
        queryAnMechanism.setMechanismName(anMechanism.getMechanismName());
        List<AnMechanism> anMechanismList = anMechanismService.selectAnMechanismList(queryAnMechanism);
        if(anMechanismList.size()>0){
            return AjaxResult.error("该机构名称已存在！");
        }
        anMechanism.setApplyTime(DateUtils.getNowDate());
        anMechanism.setApplyDoneTime(DateUtils.getNowDate());
        anMechanism.setExamineStatus(1L);
        return toAjax(anMechanismService.insertAnMechanism(anMechanism));
    }

    /**
     * 修改机构
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:edit')")
    @Log(title = "机构", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AnMechanism anMechanism) {
        if (anMechanism.getExamineStatus() == 1) {
            AnMechanism anMechanism1 = anMechanismService.selectAnMechanismByMechanismId(anMechanism.getMechanismId());
            if (anMechanism1.getWechatUserId() != null) {
                AnWechatUser anWechatUser = anWechatUserService.selectAnWechatUserByWechatUserId(anMechanism1.getWechatUserId());
                anWechatUser.setIsMechanism(0L);
                anWechatUserService.updateAnWechatUser(anWechatUser);
            }
            anMechanism.setApplyDoneTime(DateUtils.getNowDate());
        }
        return toAjax(anMechanismService.updateAnMechanism(anMechanism));
    }

    /**
     * 删除机构
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:remove')")
    @Log(title = "机构", businessType = BusinessType.DELETE)
    @DeleteMapping("/{mechanismIds}")
    public AjaxResult remove(@PathVariable Long[] mechanismIds) {
        return toAjax(anMechanismService.deleteAnMechanismByMechanismIds(mechanismIds));
    }


    /**
     * 机构推广二维码列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:list')")
    @GetMapping("/qr_code/list")
    public TableDataInfo mechanismQrCodeList(AnMechanismMember anMechanismMember) {
        startPage();
        anMechanismMember.setMechanismId(anMechanismMember.getMechanismId());
        List<AnMechanismMember> anMechanismMembers = anMechanismMemberService.selectAnMechanismMemberList(anMechanismMember);
        return getDataTable(anMechanismMembers);
    }


    /**
     * 生成机构推广二维码
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('an:mechanism:add')")
    @PostMapping("/create_qr_code")
    public AjaxResult createQrCode(HttpServletRequest request, @RequestBody AnMechanismMember anMechanismMember) {
        anMechanismMember.setMechanismId(anMechanismMember.getMechanismId());
        AnMechanism anMechanism = anMechanismService.selectAnMechanismByMechanismId(anMechanismMember.getMechanismId());
        if (anMechanism.getExamineStatus() != 1) {
            return AjaxResult.error("该机构未通过审核，无法添加推广码！");
        }
        anMechanismMember.setWechatUserId(anMechanism.getWechatUserId());
        AnMechanismMember mechanismMember = anMechanismMemberService.createQrCode(anMechanismMember);
        if (mechanismMember == null) {
            return AjaxResult.error("该推广码已存在！");
        }
        return AjaxResult.success(mechanismMember);
    }

    /**
     * 删除推广二维码
     *
     * @return
     */
    @DeleteMapping("/qr_code/{mechanismMemberIds}")
    public AjaxResult removeQrCode(@PathVariable Long[] mechanismMemberIds) {
        for (Long mechanismMemberId : mechanismMemberIds) {
            AnWechatUserMechanism anMechanismMember = new AnWechatUserMechanism();
            anMechanismMember.setMechanismMemberId(mechanismMemberId);
            List<AnWechatUserMechanism> anWechatUserMechanismList = anWechatUserMechanismService.selectAnWechatUserMechanismList(anMechanismMember);
            //有推广数据的不能删除
            if (anWechatUserMechanismList.size() > 0) {
                return AjaxResult.error("该推广码下有绑定用户，无法删除！");
            }
        }
        anMechanismMemberService.deleteAnMechanismMemberByMechanismMemberIds(mechanismMemberIds);
        return success();
    }
}
